import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/http_service/http_attachment_service.dart';
import 'package:finance_app/src/widgets/bottom_sheet/attachments_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/photo_preview_bottom_sheet.dart';
import 'package:flutter/material.dart';

mixin FormAttachMixin<T> on BaseProvider<T> {
  List<String> files = [];

  List<OcrAttachmentEntity> get attachments;

  void unFocus();

  void onAddAttachment() {
    unFocus();
    obtainContext?.call((context) async {
      final result = await showAttachmentsBottomSheet(context);
      if (result != null) {
        files.add(result);
        update();
      }
    });
  }

  void onSelectFile(String value) {
    unFocus();
    obtainContext?.call((context) async {
      bool isSelect = await showPhotoPreviewBottomSheet(
          context, File(value), null,
          canDelete: true);
      if (isSelect == true) {
        await showDeleteAttachmentInfoBottomSheet(context, onCancel: () {
          Navigator.of(context).pop();
        }, onDelete: () {
          Navigator.of(context).pop();
          files.remove(value);
          update();
        });
      }
    });
  }

  bool get isEdit;

  void onSelectAttachment(OcrAttachmentEntity value) {
    unFocus();
    obtainContext?.call((context) async {
      bool isSelect = await showPhotoPreviewBottomSheet(context, null, value,
          canDelete: isEdit == true);
      if (isSelect == true) {
        await showDeleteAttachmentInfoBottomSheet(context, onCancel: () {
          Navigator.of(context).pop();
        }, onDelete: () {
          Navigator.of(context).pop();
          attachments.remove(value);
          update();
        });
      }
    });
  }

  Future<List<int>> uploadFiles() async {
    List<int> attachmentIds = [];
    obtainContext?.call((context) {
      BaseConfig.dialogBase
          .showLoadingDialog(context: context, text: S.current.loading);
    });
    if (files.length > 0) {
      for (final item in files) {
        await post(
            HttpAttachmentService.createAttachment(
              item,
            ), onSuccess: (result) {
          final data = getEntityFromResult<OcrAttachmentEntity>(result);
          attachmentIds.add(data.id);
        });
      }
    }

    if (attachmentIds.length != files.length) {
      showToast(S.current.file_upload_failure);
      obtainContext?.call((context) {
        Navigator.of(context).pop();
      });
      return null;
    }
    if (attachments != null) {
      attachmentIds.addAll(attachments.map((e) => e.id));
    }
    obtainContext?.call((context) {
      Navigator.of(context).pop();
    });
    return attachmentIds;
  }
}
